package com.imyours.webservice.services;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.imyours.model.team.TeamEntity;
import com.imyours.model.user.UserEntity;
import com.imyours.model.util.HibernateUtil;
import com.imyours.users.session.UserSessionManager;
import com.imyours.webservice.service.Context;
import com.imyours.webservice.service.ContextService;
import com.imyours.webservice.services.annotation.Service;

@Service(name = "friendList")
public class FriendList extends ContextService {

	public FriendList(Context context) {
		super(context);
	}

	public void execute() {
		String sessionId = context.getParameter().get("sessionId");
		if (sessionId != null) {
			UserEntity user = UserSessionManager.getInstance().getUser(sessionId);
			if (user != null) {
				SessionFactory sf = HibernateUtil.getSessionFactory();
				Session se = sf.openSession();
				Query query = se.createQuery("from TeamEntity where user = ? order by teamOrder asc ").setEntity(0, user);
				List<TeamEntity> teams = query.list();
				List<Map<String, Object>> resultMaps = new ArrayList<Map<String, Object>>();
				Map<String, Object> teamMap = null;
				Map<String,String> userMap = null;
				for (int i = 0; i < teams.size(); i++) {
					teamMap = new HashMap<String, Object>();
					teamMap.put("id", teams.get(i).getId());
					teamMap.put("name", teams.get(i).getName());
					teamMap.put("order", teams.get(i).getOrder());
					logger.info("teamName:"+teams.get(i).getName());
					List<Map<String,String>> userList = new ArrayList<Map<String,String>>();
					for (UserEntity ue : teams.get(i).getUsers()) {
						userMap = new HashMap<String, String>();
						userMap.put("id", "" + ue.getId());
						userMap.put("nickName", ue.getNickname());
						userList.add(userMap);
					}
					teamMap.put("users",userList);
					resultMaps.add(teamMap);
				}
				se.close();
				context.setResult(new HashMap<String, Object>());
				context.getResult().put("teams", resultMaps);
				context.success();
			} else {
				context.fail(2, "invalidate sessionId");
			}
		}

	}

}
